<template>
  <div id="virtualRecharge" class="c-p">
    <div style="z-index: -1" class="c-w100 c-hh140 theme-bg-gradient180 c-pt40">
      <div class="c-flex-row c-justify-sb c-aligni-center">
        <div class="c-fc-white c-pl24 c-flex-row c-aligni-center">
          <span class="c-fs24">{{giftCardName}}余额：</span>
          <span class="c-fs40">{{userCoinAmount}}</span>
        </div>
        <div @click="goGiftCardRecord" class="record-btn-bg theme-fc c-fs22 c-hh44 c-pl16 c-pr10 c-flex-row c-flex-center c-br-tl36 c-br-bl36">{{giftCardName}}明细</div>
      </div>
    </div>
    <div v-if="!!giftCardPackList.length" style="margin-top: -0.5rem" class="c-bg-white c-w100 c-br-tr20 c-br-tl20 c-ph18 c-pb30">
      <div class="c-fs22 c-fc-sblack c-pt20">充值{{giftCardName}}</div>
      <div class="c-flex-row c-flexw-wrap">
        <div @click="chooseIndex(index, item.rechargeMoney, item.id)" v-for="(item, index) in giftCardPackList" :key="index" :class="[ (index + 1) % 3 == 0 ? '' : ' c-mr14']" class="c-p box-s c-ww192 c-hh140 c-mt24 c-br8">
          <div class="c-bg-f569 c-w100 c-h c-flex-column c-flex-center c-br8" :class="index == currentIndex ? 'theme-bd2' : ''">
            <div class="c-pa c-p-l0 c-p-tm8 c-hh26 c-fc-white give-br c-ph8 theme-bg c-fs18" v-if="item.giveNumber && Number(item.giveNumber) > 0">送{{item.giveNumber}}{{giftCardName}}</div>
            <div class="c-fc-xblack c-ph6 c-textAlign-c c-fs20 c-mt10">
              <span class="c-fs28 c-fw600 c-mr2">{{item.coinNumber}}</span>{{giftCardName}}
            </div>
            <div class="c-fc-gray c-fs24 c-textAlign-c c-mt10">
              <span class="c-mr2 c-fs20">￥</span>
              <span class="">{{item.rechargeMoney}}</span>
            </div>
          </div>
        </div>
      </div>
      <div v-if="!!isCustomAmount" class="c-mt30 c-pb16 c-bd-b1">
        <input type="number" placeholder="自定义币数量" @input="inputEnter(e)" @focus="inputFocus" v-model="inputCount" class="c-fc-xblack c-textAlign-l c-fs28 c-bd0 c-w100"/>
      </div>
      <div v-if="!!isCustomAmount" class="c-mt20 c-lh34 c-fs22 c-fc-sblack">{{proportion}}币=1.00元人民币</div>
      <div @click="openPayPopup" :class="Number(totalPrice) > 0 ? '' : 'c-opacity50'" class="c-hh76 c-mt52 c-br40 c-fc-white theme-bg c-flex-row c-flex-center c-fs28 c-mh10">
        确认充值￥{{totalPrice}}
      </div>
      <template v-if="protocolInfo">
        <div class="c-mt20 c-fs20 theme-fc c-lh42" @click="isCheckAgreement = !isCheckAgreement">
          <i class="c-textAlign-r iconfont c-fs24 c-lh c-pr16" :class="isCheckAgreement ? 'theme-fc' : 'c-fc-gray'">{{isCheckAgreement ? '&#xe6b1;' : '&#xe692;'}}</i>
          <span class="c-fc-sblack">已阅读并同意</span>
          <span @click.stop="clickProtocol(item)" v-for="(item, index) in protocolInfo" :key="index">《{{item.name}}》</span>
        </div>
      </template>
      <div v-if="baseInfo" class="c-mt40 c-lh38 c-fs22 c-fc-sblack c-ph20 c-pv20 c-bg-f8 c-br20">
        <p class="c-fc-sblack c-mb6 c-fw600">充值说明</p>
        <pre class="c-fs22 c-fc-gray">{{baseInfo.description}}</pre>
      </div>
    </div>
    <!-- 支付弹窗 -->
    <pay-template v-if="openModal" :ckFrom="190" :totalCoin="currentIndex > -1 && giftCardPackList[currentIndex] ? (giftCardPackList[currentIndex].coinNumber + giftCardPackList[currentIndex].giveNumber) : (inputCount || 0)" :balance="Number(balance) || 0" :totalPrice="Number(totalPrice) * 1" :isCanUseGiftCard="false" :enablePayMall="!!(payConf && payConf.enablePayKnowledge == 1)" :enableWxpay="!!(payConf && payConf.enableWxpay == 1)" @clickPayType="clickPayType" @closePay="closeModal"></pay-template>
    <pay-password v-show="showPassword" :price="totalPrice" @hidePwd="hidePwd" @confirmPwd="confirmPwd"></pay-password>
  </div>
</template>

<script>
import { utilJs } from "@/utils/common.js";
import payPassword from "@/components/templates/common/pay/payPassword.vue";
import PayTemplate from "@/components/templates/common/pay/payTemplate.vue";
let isClick = false;
let orderId = -1;
const limitMoney = 10000; // 可充值的最高金额
export default {
  name: "RechargeCard",
  components: {
    payPassword,
    PayTemplate
  },
  beforeCreate() { },
  data() {
    return {
      inputCount: '',
      currentIndex: -1, // 当前选中的套餐
      totalPrice: 0, // 需要支付的金额
      openModal: false,
      payType: 0, //0是微信支付，1是余额支付
      password: "",
      showPassword: false,
      giftCardPackList: [],
      proportion: 0, // 兑换比例
      baseInfo: null, // 虚拟充值基本信息
      balance: 0, // 账户余额（金额）
      userCoinAmount: 0, // 虚拟币余额
      prodId: 0,
      giftCardName: '',
      giftCardPic: '',
      isCustomAmount: 0, // 是否开启自定义输入币数量
      protocolInfo: null, // 服务协议
      diyPackageId: 0, // 自定义币数量的prodid
      isCheckAgreement: true, // 默认勾选协议
      routeQuery: null, // 用于coursePay跳转过来充值后跳转回去的参数对象
      rechargeFrom: 0, // 1 payCom 跳转过来的，要跳转回去
      payConf: {},
    };
  },
  created() {
    utilJs.appShare(this);
  },
  mounted() {
  },
  computed: {
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      if (!(to.query.isGoldPlan && to.query.isGoldPlan == 1 && localStorage.getItem("shopPayBack"))) {
        vm.pathFrom = from.fullPath;
      }
    });
  },
  methods: {
    clickProtocol(item) {
      this.$routerGo(this, "push", { path: `/homePage/agent/protocolInfo`, query: { protocolId: item.protocolId || 0 } });
    },
    // 获取虚拟充值服务协议
    getProdProtocol() {
      utilJs.getMethod(`${global.apiurl}protocols/getProtocolByProdType?prodType=190`, (res) => {
        this.protocolInfo = res.protocol && res.protocol.length > 0 ? res.protocol : null;
        this.isCheckAgreement = res && res.relatesType == 1 ? true : false;
      });
    },
    getGiftCardPackList() {
      utilJs.getMethod(global.apiurl + `giftCard/getGiftCardPackList`, res => {
        this.giftCardPackList = res.packageList;
        this.baseInfo = res.baseInfo || {};
        this.proportion = this.baseInfo.proportion || 0;
        this.userCoinAmount = res.userCoinAmount;
        this.balance = res.balance;
        this.isCustomAmount = this.baseInfo.isCustomAmount || 0
        this.diyPackageId = res.diyPackageId || 0;
        this.payConf = res.payConf || {};
      })
    },
    hidePwd() {
      this.showPassword = false;
    },
    confirmPwd(pwd) {
      this.password = pwd;
      this.yuePay();
    },
    getOrderId() {
      if (isClick) {
        return;
      }
      isClick = true;
      this.payType = Number(this.totalPrice) == 0 ? 1 : this.payType;
      let data = {
        extGroupId: '', //分销拼团groupId
        isCaptain: '', //分销拼团 1 是团长 0 不是
        companyId: '', //分销的内容方id
        inviteId: -1, //社群邀请人ID，用来绑定邀请进社群的关系
        prodId: !this.prodId ? this.diyPackageId : this.prodId,
        usePoint: 0,
        payMoney: Number(this.totalPrice).toFixed(2),
        payMethod: this.payType == 0 ? 1 : this.payType == 3 ? 20 : 2, // 20是支付宝，14是虚拟花瓣，1微信，2余额
        useCoupon: '',
        collageId: '',
        groupId: '',
        fromInvite: 0,
        prodType: '190',
        subProdId: '',
        coinNumber: this.inputCount || 0,
      };
      if (sessionStorage.getItem('promotedAccountId')) {
        data.promotedAccountId = sessionStorage.getItem('promotedAccountId')
      }
      //携带当前进入的时候的分享人id过去后端做数据分析
      const xTraceSid = sessionStorage.getItem('shareFromUserId') || '';
      if (xTraceSid) {
        data['x-trace-sid'] = xTraceSid;
      }
      utilJs.postMethod(`${global.apiurl}orders/submitOrder`, data, res => {
        isClick = false;
        orderId = res.orderId;
        if (orderId == -1) {
          this.$showCjToast({
            text: "订单提交失败，请重新提交！",
            type: "warn",
          });
          return;
        }
        if (res.code == 201) {
          this.$showCjToast({
            text: "支付成功",
            type: "success",
          })
          this.paySuccess();
          return;
        }
        if (this.payType == 1) {
          this.showPassword = true;
        } else if (this.payType == 3) { // 支付宝支付
          utilJs.postMethod( global.apiurl + "payment/alipayConf", {orderId: orderId}, (aliRes) => {
            this.$routerGo(this, "replace", { path: "/homePage/course/aliPayMiddlePage", query: {orderId: aliRes.orderNo} });
          });
        } else {
          this.wePay();
        }
      },
        failRes => {
          isClick = false;
        });
    },
    paySuccess() {
      if (!!this.routeQuery) { // 若是routeQuery有值，则返回coursePay继续支付
        let routeQuery = JSON.parse(this.routeQuery)
        console.log(routeQuery);
        if (routeQuery.isComeFrom == 'mallOrderDetail') {
          delete routeQuery.isComeFrom;
          this.$routerGo(this, "replace", {path: '/mall/mallOrder/orderDetail', query: routeQuery})
          return;
        } else if (routeQuery.shopNo) {
          this.$routerGo(this, "replace", {path: `/mall/shopDetail/shopDetail?shopNo=${routeQuery.shopNo}${routeQuery.goodsRoomId ? '&goodsRoomId=' + routeQuery.goodsRoomId : ''}`})
          return;
        } else if (routeQuery.shopNo == '') {
          this.$routerGo(this, "replace", {path: '/mall/shopCart/shopCart'})
          return;
        } else if (routeQuery.isComeFrom == 'vipBuy') {
          this.$routerGo(this, "replace", {path: '/member/vip/vipBuy', query: routeQuery})
          return;
        } else {
          this.$routerGo(this, "replace", {path: '/homePage/course/coursePay', query: routeQuery})
          return;
        }
      }
      if (this.rechargeFrom == 1) {
        this.$router.go(-1)
        return;
      }
      this.initData();
      this.getGiftCardPackList();
      this.getProdProtocol();
    },
    yuePay() {
      if (this.password == "") {
        this.$showCjToast({
          text: "请输入支付密码",
          type: "warn",
        });
        return;
      }
      let data = {
        orderId: orderId,
        payPwd: this.password
      };
      if (sessionStorage.getItem('promotedAccountId')) {
        data.promotedAccountId = sessionStorage.getItem('promotedAccountId')
      }
      let that = this;
      utilJs.yuePay(data, function () {
        that.showPassword = false;
        that.$showCjToast({
          text: "支付成功",
          type: "success",
        }).then(() => {
          that.paySuccess()
        });
      }, function () {

      });
    },
    wePay() {
      let data = {
        orderId: orderId
      };
      let u = navigator.userAgent;
      let isAndroid = u.indexOf('APPLogin') > -1; //android终端
      let isiOS = u.indexOf('IOSLogin') > -1; //ios终端
      let isNewiOS = u.indexOf('IOSNewLogin') > -1 || navigator.userAgent.indexOf("IOSNewApp") > -1; //ios终端
      if (isAndroid == true || isiOS == true || isNewiOS == true) {
        utilJs.appPay(data, "FALSE", 0, this.ckFrom, 0, '');
      } else {
        let isWechatH5Pay = !utilJs.isWeiXin() && utilJs.isMobileUserAgent() && !utilJs.isIOSAppALL() && !utilJs.isAndroidApp();
        let goUrl = this.$route.path ? window.location.href.split("#")[0] + '#' + this.$route.path : window.location.href;
        let payFromPath = goUrl;
        if (!!this.routeQuery) { // 若是routeQuery有值，则返回coursePay继续支付
          localStorage.setItem("shopPayBack", this.routeQuery);
          goUrl = goUrl + (goUrl.split('?').length > 2 ? "&" : "?") + "isGoldPlan=1";
          if (isWechatH5Pay) {
            payFromPath = window.location.href.split("#")[0] + '#' + (this.pathFrom || '/')
            localStorage.setItem("payFromPath", payFromPath);
            goUrl = goUrl + (goUrl.split('?').length > 2 ? "&" : "?") + "isWechatH5Pay=1";
          }
        }
        data.goUrl = goUrl;
        if (sessionStorage.getItem('promotedAccountId')) {
          data.promotedAccountId = sessionStorage.getItem('promotedAccountId')
        }
        utilJs.wechatPay(data, () => {
          this.paySuccess();
        });
      }
    },
    openPayPopup() {
      if (this.isCheckAgreement == false && this.protocolInfo) {
        this.$showCjToast({
          text: '请勾选协议后进行充值',
          type: "warn",
        });
        return
      }
      if (!this.totalPrice) {
        return;
      }
      // 充值前需要确认是否绑定手机，绑定手机才能充值
      if (!localStorage.getItem("uMobile")) {
        if (utilJs.goBindMobile()) return;
      }
      if (!!this.inputCount && (Number(this.inputCount) % this.proportion != 0 || Number(this.inputCount) > (Number(this.proportion) * limitMoney))) {
        let msg = (Number(this.inputCount) % this.proportion != 0) ? `请输入${this.proportion}的倍数哦` : `充值金额不能高于${limitMoney}元`
        this.$showCjToast({
          text: msg,
          type: "warn"
        });
        this.inputCount = '';
        this.totalPrice = 0;
        return
      }
      this.openModal = true
    },
    clickPayType(type) {
      this.payType = type;
      this.getOrderId()
    },
    closeModal() {
      this.openModal = false
    },
    inputEnter() {
      let total = (Number(this.inputCount) / this.proportion).toFixed(2);
      if (total > limitMoney) {
        this.$showCjToast({
          text: `充值金额不能高于${limitMoney}元`,
          type: "warn"
        });
        this.inputCount = this.proportion * limitMoney;
        this.totalPrice = limitMoney;
        return;
      }
      this.totalPrice = total > 0 ? total : 0;
    },
    inputFocus() { // 点击自定义输入框，默认取消选择套餐
      if (!!this.prodId) {
        this.currentIndex = -1;
        this.totalPrice = 0;
        this.prodId = 0;
      }
    },
    chooseIndex(index, rechargeMoney, prodId) {
      if (this.currentIndex != -1 && this.currentIndex == index) {
        return
      }
      this.inputCount = '';
      this.prodId = prodId;
      this.currentIndex = this.currentIndex != index ? index : -1;
      this.totalPrice = rechargeMoney;
    },
    goGiftCardRecord() {
      this.$routerGo(this, "push", { path: '/member/giftCard/giftCardRecord'});
    },
    //分享
    wechatShare: function () {
      let shareUrl =
        window.location.href.split("#")[0] +
        "#" +
        this.$route.path +
        "?refereeId=" +
        localStorage.getItem("userId");
      utilJs.wechatConfig(shareUrl, "", "", "", function () { });
    },
    //手机端分享
    appShare: function () {
      let shareUrl =
        window.location.href.split("#")[0] +
        "#" +
        this.$route.path +
        "?refereeId=" +
        localStorage.getItem("userId");
      utilJs.appShareTrue("", "", shareUrl, "");
    },
    initData() {
      setDocumentTitle("我的账户");// eslint-disable-line
      this.inputCount = '';
      this.currentIndex = -1;
      this.totalPrice = 0;
      this.openModal = false;
      this.payType = 0;
      this.password = "";
      this.showPassword = false;
      this.giftCardPackList = [];
      this.proportion = 0;
      this.baseInfo = null;
      this.balance = 0;
      this.userCoinAmount = 0;
      this.prodId = 0;
      this.diyPackageId = 0;
      this.isCustomAmount = 0;
      this.routeQuery = sessionStorage.getItem('giftCardBack') || null;
      // if (sessionStorage.getItem('giftCardBack')) {
      //   sessionStorage.removeItem('giftCardBack');
      // }
      this.rechargeFrom = this.$route.query.rechargeFrom || 0;
      if (this.$route.query.isWechatH5Pay == 1 && localStorage.getItem("payFromPath")) {
        let payFromPath = localStorage.getItem("payFromPath");
        localStorage.removeItem("payFromPath")
        localStorage.removeItem("shopPayBack")
        window.location.replace(payFromPath)
        return;
      } else if (this.$route.query.isGoldPlan == 1 && localStorage.getItem("shopPayBack")) { //微信支付后点击回到这个页面--点金计划
        let shopPayBack = JSON.parse(localStorage.getItem("shopPayBack"));
        localStorage.removeItem("shopPayBack")
        this.$routerGo(this, "replace", {path: '/homePage/course/coursePay', query: shopPayBack})
        return;
      } else if (localStorage.getItem("shopPayBack") || localStorage.getItem("payFromPath")) {
        localStorage.removeItem("shopPayBack")
        localStorage.removeItem("payFromPath")
      }
      utilJs.getGiftCardInfo().then(res => {
        this.giftCardName = res.name || '虚拟币';
        this.giftCardPic = res.coinImg || '';
      })
    },
  },
  activated() {
    this.initData();
    this.getGiftCardPackList();
    this.getProdProtocol();
  },
  deactivated() {
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.record-btn-bg {
  background: linear-gradient(90deg, rgba(255, 255, 255, 0.9) 0%, rgba(255, 255, 255, 0.7) 100%);
}
.give-br {
  border-radius: 0.3rem 0.1rem 0.3rem 0.1rem;
}
.box-s {
  box-sizing: border-box;
}
pre {
  white-space: pre-wrap!important;
  word-wrap: break-word!important;
  font-family: "Helvetica Neue", Helvetica, Roboto, Arial, sans-serif;
}
</style>
